package com.putao.interceptor;

import feign.RequestTemplate;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;

/**
 * Feign公共拦截器
 */
@Slf4j
public class CommonFeignInterceptor {

    public void apply(RequestTemplate template) {
        try {
            // 获取请求对象
            ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            if (servletRequestAttributes != null) {
                HttpServletRequest request = servletRequestAttributes.getRequest();
                Enumeration<String> headerNames = request.getHeaderNames();
                while (headerNames.hasMoreElements()) {
                    String header = headerNames.nextElement();
                    // 跳过 content-length
                    if (header.equals("content-length")){
                        continue;
                    }
                    // 获取当前请求的header，获取到jwt令牌
                    if (request.getHeader(header) != null) {
                        template.header(header, request.getHeader(header));
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
